package com.rjwh.dingdong.client.mvp.presenter.impl;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.aishua.lib.task.AsResult;
import com.aishua.lib.utils.AsStrUtils;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.webbrowser.OaGameActivity;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.bean.jsonbean.ResGetDrawBookDetailBean;
import com.rjwh.dingdong.client.bean.localbean.DownloadInfo;
import com.rjwh.dingdong.client.bean.localbean.DrawBookCommentData;
import com.rjwh.dingdong.client.bean.localbean.DrawBookDetailData;
import com.rjwh.dingdong.client.bean.localbean.DrawBookDetailExtraData;
import com.rjwh.dingdong.client.bean.localbean.DrawBookDetailModuleData;
import com.rjwh.dingdong.client.bean.localbean.GetDrawBookDetailData;
import com.rjwh.dingdong.client.bean.localbean.LocalGmaeInfo;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.constant.NetConstant;
import com.rjwh.dingdong.client.download.DownloadManager;
import com.rjwh.dingdong.client.download.ZipUnTask;
import com.rjwh.dingdong.client.mvp.BasePresenter;
import com.rjwh.dingdong.client.mvp.model.impl.DrawBookDetailModel;
import com.rjwh.dingdong.client.mvp.view.DrawBookDetailView;
import com.rjwh.dingdong.client.player.IPlayback;
import com.rjwh.dingdong.client.service.HttpWebCoreService;
import com.rjwh.dingdong.client.service.PlaybackService;
import com.rjwh.dingdong.client.util.FileUtils;
import com.rjwh.dingdong.client.util.ToastUtil;

import java.io.File;
import java.util.List;

/**
 * @author Kay
 * @ClassName DrawBookDetailPresenter
 * @Description
 * @date 2016-7-8
 * @history 2016-7-8 author: description:
 */
public class DrawBookDetailPresenter extends BasePresenter<DrawBookDetailView> {
    private Context context;
    private DrawBookDetailModel model;

    private PlaybackService mPlaybackService;
    private boolean mIsServiceBound;

    public DrawBookDetailPresenter(Context context, DrawBookDetailView mMvpView) {
        super(context, mMvpView);
        this.context = context;
        model = new DrawBookDetailModel(this);
    }

    public void doGetDrawBookDetail(String bookid) {
        if (isViewAttached()) {
            getMvpView().hideErrorView();
            getMvpView().showLoadingView();
            model.doGetDrawBookDetail(bookid);
        }
    }

    public void onServerDataAcquired(int businessType, AsResult mAsResult, boolean isRefresh) {
        if (getMvpView() != null) {
            getMvpView().hideLoadingView();
            switch (businessType) {
                case NetConstant.GETDRAWBOOKDETAIL:
                    ResGetDrawBookDetailBean resGetDrawBookViewBean = (ResGetDrawBookDetailBean) mAsResult.getObj();
                    if (mAsResult.getResultCode() > NetConstant.MSG_CONNECT_SUCCESS && resGetDrawBookViewBean != null) {
                        GetDrawBookDetailData data = resGetDrawBookViewBean.getData();
                        if (data != null) {
                            DrawBookDetailData drawbook = data.getDrawbook();
                            List<DrawBookCommentData> drawbookcommentlist = data.getDrawbookcommentlist();
                            DrawBookDetailExtraData drawbookextra = data.getDrawbookextra();
                            DrawBookDetailModuleData module = data.getModule();
                            if (drawbook != null && drawbookextra != null) {
                                getMvpView().upDateView(drawbook, drawbookextra);
                                getMvpView().setDownLoadBtnShow(true);
                            }
                            if (drawbookcommentlist != null) {
                                getMvpView().loadCommentData(drawbookcommentlist);
                            }
                            if (module != null) {
                                getMvpView().loadModuleData(module);
                            }
                        } else {
                            ToastUtil.showToast(getContext(), "绘本不存在");
                            getMvpView().setDownLoadBtnShow(false);
                        }
                    } else {
                        getMvpView().showErrorView();
                    }
                    break;

                default:
                    break;
            }
        }
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mPlaybackService = ((PlaybackService.LocalBinder) service).getService();
            getMvpView().onPlaybackServiceBound(mPlaybackService);
        }

        public void onServiceDisconnected(ComponentName className) {
            mPlaybackService = null;
            getMvpView().onPlaybackServiceUnbound();
        }
    };

    private void bindPlaybackService() {
        getContext().bindService(new Intent(getContext(), PlaybackService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsServiceBound = true;
    }

    private void unbindPlaybackService() {
        if (mIsServiceBound) {
            // Detach our existing connection.
            getContext().unbindService(mConnection);
            mIsServiceBound = false;
        }
    }

    public void subscribe() {
        bindPlaybackService();
    }

    //启动绘本
    public void startGame(int bookid, IPlayback mPlayer) {
        File file = new File(FileUtils.getDrwabookDirDirectory(), bookid + "/");
        if (file.isDirectory() && file.listFiles().length > 0) {
            String userid = MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_USERID);
            String babyid = MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_BABYID);
            String token = MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_USER_TOKEN);
            String uuid = MyApplication.deviceId;
            String version = MyApplication.versionCode;
            String url = String.format(HttpWebCoreService.HUIBEN_URL, bookid, userid,
                    babyid, version, uuid, token, System.currentTimeMillis(), bookid);
            OaGameActivity.startActivity(context, url);
            if (mPlayer != null && mPlayer.isPlaying()) {
                mPlayer.pause();
            }
        } else {
            ToastUtil.showToast(context, context.getString(R.string.game_filepath_error));
        }
    }

    //执行下载
    public void doDownload(DownloadInfo downloadInfo, DrawBookDetailData drawbook, int bookid) {
        if (downloadInfo == null) {
            if (drawbook == null) {
                ToastUtil.showToast(context, context.getString(R.string.download_error));
                return;
            }
            DownloadInfo dwinfo = new DownloadInfo();
            dwinfo.setGameId(bookid);
            if (AsStrUtils.isEmpty(drawbook.getBookname())) {
                ToastUtil.showToast(context, context.getString(R.string.download_name_error));
                return;
            }
            dwinfo.setGameName(drawbook.getBookname());
            if (AsStrUtils.isEmpty(drawbook.getDownloadurl())) {
                ToastUtil.showToast(context, context.getString(R.string.download_address_error));
                return;
            }
            dwinfo.setUrl(drawbook.getDownloadurl());
            if (AsStrUtils.isEmpty(drawbook.getCoverurl())) {
                ToastUtil.showToast(context, context.getString(R.string.download_cover_error));
                return;
            }
            dwinfo.setGamePic(drawbook.getCoverurl());
            dwinfo.setType(1);
            dwinfo.setVersion(drawbook.getVersion());
            DownloadManager.getInstance().addTask(dwinfo);
        } else {
            int mState = downloadInfo.getDownloadState();
            if (mState == DownloadManager.STATE_NONE || mState == DownloadManager.STATE_PAUSED || mState == DownloadManager.STATE_ERROR) {
                DownloadManager.getInstance().addTask(downloadInfo);
            } else if (mState == DownloadManager.STATE_WAITING || mState == DownloadManager.STATE_DOWNLOADING) {
                DownloadManager.getInstance().pauseTask(downloadInfo.getGameId());
            } else if (mState == DownloadManager.STATE_DOWNLOADED) {
                new Thread(new ZipUnTask(downloadInfo)).start();
            }
        }
    }

    //绘本是否已下载
    public boolean isGameNotNull(int bookid) {
        boolean result = false;
        List<LocalGmaeInfo> localGmaeInfoList = MyApplication.db.findAllByWhere(LocalGmaeInfo.class, "pid=" + bookid + " and type=1");
        if (!localGmaeInfoList.isEmpty()) {
            result = true;
        }
        return result;
    }

    //是否可升级
    public boolean isGameUpdate(String version, int bookid) {
        boolean result = false;
        List<LocalGmaeInfo> localGmaeInfoList = MyApplication.db.findAllByWhere(LocalGmaeInfo.class, "pid=" + bookid + " and type=1");
        if (!localGmaeInfoList.isEmpty()) {
            LocalGmaeInfo localGmaeInfo = localGmaeInfoList.get(0);
            if (AsStrUtils.isEmpty(version) || AsStrUtils.isEmpty(localGmaeInfo.getVersion())) {
                return false;
            }
            if (localGmaeInfo.getIsUpdate() == 1 || !version.equals(localGmaeInfo.getVersion())) {
                result = true;
            }
        }
        return result;
    }

    //是否正在升级
    public boolean isGameUpdateIng(int bookid) {
        boolean result = false;
        List<LocalGmaeInfo> localGmaeInfoList = MyApplication.db.findAllByWhere(LocalGmaeInfo.class, "pid=" + bookid + " and type=1");
        if (!localGmaeInfoList.isEmpty()) {
            LocalGmaeInfo localGmaeInfo = localGmaeInfoList.get(0);
            if (localGmaeInfo.getIsUpdate() == 2) {
                result = true;
            }
        }
        return result;
    }

    @Override
    public void detachView() {
        unbindPlaybackService();
        model.detachView();
        detachViews();
    }

}
